//
//  MineChatTableViewCell.swift
//  Exchange
//
//  Created by rui on 2018/5/8.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class TextChatTableViewCell: BaseChatTableViewCell {

    lazy var avatar: UIButton = {
        let avaBtn = UIButton()
        avaBtn.layer.cornerRadius = iconW * 0.5
        avaBtn.layer.masksToBounds = true
        avaBtn.setImage(#imageLiteral(resourceName: "login_icon"), for: .normal)
        return avaBtn
    }()
    
    lazy var bubbleView: UIImageView = {
        return UIImageView()
    }()
    
    lazy var contentLabel: UILabel = {
        let contentL = UILabel()
        contentL.numberOfLines = 0
        contentL.textAlignment = .left
        contentL.font = kChatTextFont
        return contentL
    }()
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.addSubview(bubbleView)
        self.addSubview(avatar)
        self.addSubview(contentLabel)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func setModel() {
        guard let m = model else { return }
        self.contentLabel.text = m.text
        avatar.frame = CGRect(x: iconMargin, y: iconTopMargin, width: iconW, height: iconH)
        
        
        let w = 2 * (iconMargin + textMargin + iconW ) + bubMargin
        let size = m.text?.ch_sizeWithConstrained(contentLabel.font, constraintRect: CGSize(width: kSCREEN_WIDTH - w, height: CGFloat.greatestFiniteMagnitude)) ?? CGSize.zero
        
        contentLabel.frame.size = size 
        
        bubbleView.width =  size.width + textMargin * 2 + bubMargin
        bubbleView.height = max(iconH, size.height + textMargin * 2)
        bubbleView.y = iconTopMargin
  
        
        if let atr = m.avatar, let url = URL(string: atr) {
            avatar.sd_setImage(with: url, for: UIControlState.normal, placeholderImage: #imageLiteral(resourceName: "login_icon"))
        }else {
            avatar.setImage(#imageLiteral(resourceName: "login_icon"), for: .normal)
        }
        
        if m.userType == .me {
            avatar.right = kSCREEN_WIDTH - iconMargin
            contentLabel.right = avatar.x - bubMargin - textMargin
            bubbleView.right = avatar.x
            bubbleView.image = #imageLiteral(resourceName: "me_chat_background")
            contentLabel.textColor = UIColor(hexStr: "#e7ebf4")
        } else {
            contentLabel.x = avatar.right + bubMargin + textMargin
            bubbleView.x = avatar.right
            bubbleView.image = #imageLiteral(resourceName: "friend_chat_background")
            contentLabel.textColor = UIColor(hexStr: "#393d46")
        }
        
        contentLabel.centerY = bubbleView.centerY
        
    }
}
